package com.cloud.sky.controller;

import com.cloud.sky.entity.MemberStatus;
import com.cloud.sky.entity.common.Result;
import com.cloud.sky.entity.common.ResultCode;
import com.cloud.sky.entity.dto.inner.AdminLoginDTO;
import com.cloud.sky.entity.dto.inner.MemberLoginDTO;
import com.cloud.sky.entity.po.Member;
import com.cloud.sky.entity.po.User;
import com.cloud.sky.entity.vo.CaptchaVO;
import com.cloud.sky.entity.vo.LoginVO;
import com.cloud.sky.service.LoginService;
import com.cloud.sky.service.MemberService;
import com.cloud.sky.service.UserService;
import com.cloud.sky.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * 登录相关
 *
 * @author Tyrone
 * @date 2024/8/4 17:05
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取验证码
     *
     * @param width  宽
     * @param height 高
     * @return
     */
    @GetMapping("captcha")
    public Result<CaptchaVO> captcha(@RequestParam Integer width, @RequestParam Integer height) {
        try {
            return Result.success(loginService.getCaptcha(width, height));
        } catch (Exception e) {
            log.error("com.cloud.sky.controller.LoginController#captcha error:", e);
            return Result.failure(ResultCode.failure);
        }
    }

    /**
     * 校验验证码 （注册时可以不用调用）
     *
     * @param uuid uuid
     * @param code 输入的验证码
     * @return true 校验成功，false校验失败
     */
    @GetMapping("/verifyCaptcha")
    public Result verifyCaptcha(@RequestParam String uuid, @RequestParam String code) {
        try {
            boolean b = loginService.checkCaptcha(uuid, code);
            return Result.success(b);
        } catch (Exception e) {
            log.error("com.cloud.sky.controller.LoginController#verifyCaptcha error:", e);
            return Result.failure(ResultCode.failure);
        }
    }

    /**
     * 后台登陆
     *
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/admin/login")
    public Result<LoginVO<User>> login(@RequestBody @Validated AdminLoginDTO adminLoginDTO) {
        if (!inTestOp() && !loginService.checkCaptcha(adminLoginDTO.getUuid(), adminLoginDTO.getCode())) {
            return Result.failure("验证码校验失败");
        }
        User user = userService.getUserByUsername(adminLoginDTO.getUsername());
        if (user == null) {
            return Result.failure("不存在该用户");
        }
        if (!Objects.equals(MD5Util.encrypt(adminLoginDTO.getPassword()), user.getPassword())) {
            return Result.failure("密码错误");
        }
        String adminToken = loginService.getAdminToken(user.getId());
        if (StringUtils.isBlank(adminToken)) {
            return Result.failure(ResultCode.failure);
        }
        return Result.success(new LoginVO<>(adminToken, user));
    }

    /**
     * 后台注册
     *
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/admin/register")
    public Result<LoginVO<User>> register(@RequestBody AdminLoginDTO adminLoginDTO) {
        User userByUsername = userService.getUserByUsername(adminLoginDTO.getUsername());
        if (!inTestOp() && !loginService.checkCaptcha(adminLoginDTO.getUuid(), adminLoginDTO.getCode())) {
            return Result.failure("验证码校验失败");
        }
        if (userByUsername != null) {
            return Result.failure("用户已存在");
        }
        User user = new User();
        user.setPassword(MD5Util.encrypt(adminLoginDTO.getPassword()));
        user.setUsername(adminLoginDTO.getUsername());
        user.setCreateTime(new Date());
        boolean save = userService.save(user);
        if (save) {
            String adminToken = loginService.getAdminToken(user.getId());
            return Result.success(new LoginVO<>(adminToken, user));
        }
        return Result.failure(ResultCode.failure);
    }


    /**
     * 前台登录
     *
     * @param memberLoginDTO
     * @return
     */
    @PostMapping("/portal/login")
    public Result<LoginVO<Member>> login(@RequestBody MemberLoginDTO memberLoginDTO) {
        Member member = memberService.getByOpenId(memberLoginDTO.getOpenId());
        if (member == null) {
            member = new Member();
            member.setOpenId(memberLoginDTO.getOpenId());
            member.setCreateTime(new Date());
            member.setStatus(MemberStatus.UN_BIND.getCode());
            boolean save = memberService.save(member);
            if (save) {
                String memberToken = loginService.getMemberToken(member.getId());
                return Result.success(new LoginVO<>(memberToken, member));
            }
            return Result.failure(ResultCode.failure);
        } else {
            String memberToken = loginService.getMemberToken(member.getId());
            return Result.success(new LoginVO<>(memberToken, member));
        }

    }

    private static Boolean inTestOp() {
        return MDC.get("inTestOp") != null;
    }


}
